﻿using System;
using System.Collections.Generic;
using System.Web.Script.Services;
using System.Web.Services;
using DAL.POCO;
using DAL.Repositories;
using GameAdmin.Classes;

namespace GameAdmin.Services
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class DesignerService : System.Web.Services.WebService
    {
        [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
        public string UpdateFields(int roundId, string serializedFields)
        {
            Dictionary<string, int> fieldTypes = HelperMethods.GetFieldTypesReverse();
            List<Field> fields = new List<Field>();
            string[] serializedRows = serializedFields.Split(';');

            // create Field objects
            foreach (string row in serializedRows)
            {
                string[] attributes = row.Split('-');
                string[] coords = attributes[0].Split(',');

                Field f = new Field();
                f.roundId = roundId;
                f.x = Int32.Parse(coords[0]);
                f.y = Int32.Parse(coords[1]);
                f.type = fieldTypes[attributes[1]];

                if (attributes[1] == "guardian")
                {
                    f.radiusGuard = Int32.Parse(attributes[2]);
                    f.difficulty = Int32.Parse(attributes[3]);
                }
                else if (attributes[1] == "question") f.difficulty = Int32.Parse(attributes[2]);

                fields.Add(f);
            }

            // delete existing fields from db (should be faster than to check field by field, whether it exists in db or not)
            FieldRepository.DeleteFields(roundId);

            // insert to db
            FieldRepository.InsertFields(roundId, fields);

            return "Úspěšně bylo přidaných " + fields.Count + " polí";
        }
    }
}
